Module modAP

    Private dtBP As DataTable
    Private dtcsCnt As DataTable
    Private dtPURHDr As DataTable
    Private dtAPCNHDr As DataTable
    Private dtItem As DataTable
    Private dtAC As DataTable

    Public Function UploadAP(ByVal sSubFolder As String, ByRef sErrdesc As String) As Long

        'Event      :   UploadAP()
        'Purpose    :   For Checking Errors & updation of data in SAP from AR CSV Files
        'Author     :   Sri
        'Date       :   25 Nov 2013   

        Dim sFuncName As String = String.Empty
        Dim IsFileExist As Boolean
        Dim sFileType As String = String.Empty
        Dim oDvHdr As DataView = Nothing
        Dim oDvDtl As DataView = Nothing
        Dim sFileName As String = String.Empty

        Try
            sFuncName = "UploadAP"
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting Function", sFuncName)

            Dim DirInfo As New System.IO.DirectoryInfo(p_oCompDef.sInboxDir & "\" & sSubFolder)
            Dim files() As System.IO.FileInfo

            files = DirInfo.GetFiles("*AP*.csv")

            For Each File As System.IO.FileInfo In files
                IsFileExist = True
                sFileType = Replace(File.Name, ".csv", "").Trim
                If Right(sFileType, 3) = "Dtl" Then
                    oDvDtl = GetDataViewFromCSV(File.FullName)
                Else
                    oDvHdr = GetDataViewFromCSV(File.FullName)
                    sFileName = File.Name
                End If
            Next

            If IsFileExist = False Then
                If p_iDebugMode = DEBUG_ON Then WriteToLogFile_Debug("No AP CSV available for updation", sFuncName)
            Else
                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling Function ProcessAPFile()", sFuncName)
                If ProcessAPFile(oDvHdr, oDvDtl, sFileName, sErrdesc) <> RTN_SUCCESS Then
                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling Function FileMoveToArchive()", sFuncName)
                    For Each file As System.IO.FileInfo In files
                        AddDataToTable(p_oDtError, file.Name, "Error", sErrdesc)
                        FileMoveToArchive(file, file.FullName, RTN_ERROR)
                    Next
                    'Throw New ArgumentException(sErrdesc)
                Else
                    For Each file As System.IO.FileInfo In files
                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling Function FileMoveToArchive()", sFuncName)
                        FileMoveToArchive(file, file.FullName, RTN_SUCCESS)
                    Next
                End If
            End If

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Function Completed Successfully.", sFuncName)
            UploadAP = RTN_SUCCESS
        Catch ex As Exception
            UploadAP = RTN_ERROR
            If RollBackTransaction(sErrdesc) <> RTN_SUCCESS Then Throw New ArgumentException(sErrdesc)
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Error in uploading AP File", sFuncName)
            Call WriteToLogFile(ex.Message, sFuncName)
        End Try
    End Function

    Private Function ProcessAPFile(ByVal oDvHdr As DataView, ByVal oDvDtl As DataView, ByVal sFileName As String, ByRef sErrdesc As String) As Long

        Dim sFuncName As String = "ProcessAPFile"
        Dim oDtHdr As New DataTable
        Dim oDIComp() As SAPbobsCOM.Company = Nothing
        Dim oDt As DataTable
        Dim dt As DataTable
        Dim sSQL As String = String.Empty

        Try
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting Function", sFuncName)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("getting distinct DBs in the file.", sFuncName)
            oDt = oDvHdr.Table.DefaultView.ToTable(True, "F1")
            ReDim oDIComp(oDt.Rows.Count)

            For j As Integer = 0 To oDt.Rows.Count - 1

                sSQL = "SELECT ""Code"" FROM ""@AI_TB01_COMPANYDATA"""
                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("EXECUTING SQL :" & sSQL, sFuncName)
                dt = ExecuteSQLQueryForDT(sSQL)

                dt.DefaultView.RowFilter = "Code = '" & oDt.Rows(j).Item(0).ToString & "'"
                If dt.DefaultView.Count = 0 Then
                    sErrdesc = "Owner Entity Code ::" & oDt.Rows(j).Item(0).ToString & " provided does not exist in SAP."
                    Call WriteToLogFile(sErrdesc, sFuncName)
                    Throw New ArgumentException(sErrdesc)
                End If

                oDIComp(j) = New SAPbobsCOM.Company

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling ConnectToTargetCompany()", sFuncName)
                If ConnectToTargetCompany(oDIComp(j), oDt.Rows(j).Item(0).ToString, sErrdesc) <> RTN_SUCCESS Then
                    Throw New ArgumentException(sErrdesc)
                End If

                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting transaction on company database " & oDIComp(j).CompanyDB, sFuncName)
                oDIComp(j).StartTransaction()

                Dim DBRows() As DataRow = oDvHdr.Table.Select("F1='" & oDt.Rows(j).Item(0).ToString & "'")

                For Each row As DataRow In DBRows

                    sSQL = "Select ""CardCode"" From OCRD WHERE ""CardType"" = 'S'"
                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("EXECUTING SQL :" & sSQL, sFuncName)
                    dtBP = ExecuteSQLQueryForDT(sSQL, oDIComp(j).CompanyDB)

                    sSQL = "select ""PrcCode"" from OPRC"
                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("EXECUTING SQL :" & sSQL, sFuncName)
                    dtcsCnt = ExecuteSQLQueryForDT(sSQL, oDIComp(j).CompanyDB)

                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Opening a datatable for Invoice Ref.Doc NO.", sFuncName)
                    sSQL = "SELECT ""U_AI_RefDocNum"" FROM OPCH WHERE ""U_AI_RefDocNum"" IS NOT NULL"
                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("EXECUTING SQL :" & sSQL, sFuncName)
                    dtPURHDr = ExecuteSQLQueryForDT(sSQL, oDIComp(j).CompanyDB)

                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Opening a datatable for Invoice Ref.Doc NO.", sFuncName)
                    sSQL = "SELECT ""U_AI_RefDocNum"" FROM ORPC WHERE ""U_AI_RefDocNum"" IS NOT NULL"
                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("EXECUTING SQL :" & sSQL, sFuncName)
                    dtAPCNHDr = ExecuteSQLQueryForDT(sSQL, oDIComp(j).CompanyDB)

                    sSQL = "SELECT ""AcctCode"" FROM OACT"
                    If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("EXECUTING SQL :" & sSQL, sFuncName)
                    dtAC = ExecuteSQLQueryForDT(sSQL, oDIComp(j).CompanyDB)

                    If row.Item(1).ToString = "PUR" Or row.Item(1).ToString = "PCN" Then
                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling AddApInvoice for Document N0:::" & row(2).ToString, sFuncName)
                        Dim iInvNo As Integer

                        If AddAPInvoice(oDIComp(j), row, oDvDtl, iInvNo, sFileName, sErrdesc) <> RTN_SUCCESS Then
                            Throw New ArgumentException(sErrdesc)
                        End If

                        ' Modified for Copayment
                        'If Not IsDBNull(row.Item(15)) Then
                        '    If CDbl(row.Item(15)) > 0 Then
                        '        If AddAPInvoice_Copayment(oDIComp(j), row, oDvDtl, iInvNo, sFileName, sErrdesc) <> RTN_SUCCESS Then
                        '            Throw New ArgumentException(sErrdesc)
                        '        End If
                        '    End If
                        'Else
                        '    If CDbl(row.Item(15)) = 0 Then
                        '        If AddAPInvoice(oDIComp(j), row, oDvDtl, iInvNo, sFileName, sErrdesc) <> RTN_SUCCESS Then
                        '            Throw New ArgumentException(sErrdesc)
                        '        End If
                        '    End If
                        'End If

                        'If Not IsDBNull(row.Item(15)) Then
                        '    If CDbl(row.Item(15)) > 0 Then
                        '        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling AddOutgoingPayment for Cardcode:::" & row(4).ToString, sFuncName)
                        '        If AddOutgoingPayment(oDIComp(j), iInvNo, row, sErrdesc) <> RTN_SUCCESS Then
                        '            Throw New ArgumentException(sErrdesc)
                        '        End If
                        '    End If
                        'End If


                    ElseIf row.Item(1).ToString = "PDN" Then
                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Calling Add AP CreditNote for Document N0:::" & row(2).ToString, sFuncName)
                        If AddAPCreditNote(oDIComp(j), row, oDvDtl, sFileName, sErrdesc) <> RTN_SUCCESS Then
                            Throw New ArgumentException(sErrdesc)
                        End If
                    End If
                Next
            Next

            For lCounter As Integer = 0 To UBound(oDIComp)
                If Not oDIComp(lCounter) Is Nothing Then
                    If oDIComp(lCounter).Connected = True Then
                        If oDIComp(lCounter).InTransaction = True Then
                            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Commit transaction on company database " & oDIComp(lCounter).CompanyDB, sFuncName)
                            oDIComp(lCounter).EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit)
                        End If
                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Disconnecting company database " & oDIComp(lCounter).CompanyDB, sFuncName)
                        oDIComp(lCounter).Disconnect()
                        oDIComp(lCounter) = Nothing
                    End If
                End If
            Next

            ProcessAPFile = RTN_SUCCESS
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Fucntion completed successfully.", sFuncName)

        Catch ex As Exception
            For lCounter As Integer = 0 To UBound(oDIComp)
                If Not oDIComp(lCounter) Is Nothing Then
                    If oDIComp(lCounter).Connected = True Then
                        If oDIComp(lCounter).InTransaction = True Then
                            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Rollback transaction on company database " & oDIComp(lCounter).CompanyDB, sFuncName)
                            oDIComp(lCounter).EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack)
                        End If
                        If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Disconnecting company database " & oDIComp(lCounter).CompanyDB, sFuncName)
                        oDIComp(lCounter).Disconnect()
                        oDIComp(lCounter) = Nothing
                    End If
                End If
            Next
            ProcessAPFile = RTN_ERROR
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Error in Uploading AP File", sFuncName)
            Call WriteToLogFile(ex.Message, sFuncName)
        End Try

    End Function

    Private Function AddAPInvoice(ByVal oCompany As SAPbobsCOM.Company, _
                                  ByVal DtRow As DataRow, _
                                  ByVal oDvDtl As DataView, _
                                  ByRef iAPInvNo As Integer, _
                                  ByVal sFileName As String, _
                                  ByRef sErrDesc As String) As Long

        Dim sFuncName As String = "AddAPInvoice"
        Dim sCardCode As String = String.Empty
        Dim oDoc As SAPbobsCOM.Documents
        Dim iCnt As Integer
        Dim lRetCode, lErrCode As Long
        Dim sBatchNo As String = String.Empty
        Dim sBatchPeriod As String = String.Empty
        Dim sRemarks As String = String.Empty
        Dim oRs As SAPbobsCOM.Recordset

        Try
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting Function", sFuncName)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Creating DIAPI API Object", sFuncName)
            oDoc = oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oPurchaseInvoices)
            oRs = oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset)

            oDoc.DocType = SAPbobsCOM.BoDocumentTypes.dDocument_Service

            dtBP.DefaultView.RowFilter = "CardCode = '" & DtRow.Item(4).ToString & "'"
            If dtBP.DefaultView.Count = 0 Then
                sErrDesc = "Cardcode ::" & DtRow.Item(4).ToString & " provided does not exist in SAP."
                Call WriteToLogFile(sErrDesc, sFuncName)
                Throw New ArgumentException(sErrDesc)
            End If

            dtPURHDr.DefaultView.RowFilter = "U_AI_RefDocNum = '" & DtRow.Item(2).ToString & "'"
            If dtPURHDr.DefaultView.Count <> 0 Then
                sErrDesc = "Document NO ::" & DtRow.Item(2).ToString & " already exist in SAP."
                Call WriteToLogFile(sErrDesc, sFuncName)
                Throw New ArgumentException(sErrDesc)
            End If

            oDoc.CardCode = DtRow.Item(4).ToString
            oDoc.DocDate = DtRow.Item(3)
            oDoc.DocDueDate = DtRow.Item(3)
            oDoc.TaxDate = DtRow.Item(3)
            oDoc.NumAtCard = DtRow.Item(5).ToString
            oDoc.Comments = DtRow.Item(6).ToString
            oDoc.DocRate = CDbl(DtRow.Item(12))
            oDoc.UserFields.Fields.Item("U_AI_APARUploadName").Value = sFileName

            oDoc.UserFields.Fields.Item("U_AI_RefDocNum").Value = DtRow.Item(2).ToString

            Dim DtlRows() As DataRow = oDvDtl.Table.Select("F1='" & DtRow.Item(2).ToString & "'")

            For Each LineRow As DataRow In DtlRows
                iCnt += 1
                If iCnt > 1 Then
                    oDoc.Lines.Add()
                End If

                dtAC.DefaultView.RowFilter = "AcctCode = '" & LineRow(1).ToString & "'"
                If dtAC.DefaultView.Count = 0 Then
                    sErrDesc = "AcctCode::" & LineRow(2).ToString & "  provided does not exist in SAP."
                    Call WriteToLogFile(sErrDesc, sFuncName)
                    Throw New ArgumentException(sErrDesc)
                End If


                oDoc.Lines.AccountCode = LineRow(1).ToString
                oDoc.Lines.ItemDescription = LineRow(2).ToString
                oDoc.Lines.LineTotal = CDbl(LineRow(5))

                If CDbl(DtRow.Item(9)) > 0 Then
                    oDoc.Lines.VatGroup = "SI"
                Else
                    oDoc.Lines.VatGroup = "ZI"
                End If

                Dim sSQL As String = "SELECT T0.""PrcCode"" FROM OPRC T0 WHERE T0.""PrcCode""='" & LineRow(6).ToString & "' and T0.""DimCode"" =1"
                oRs.DoQuery(sSQL)
                If Not oRs.EoF Then
                    oDoc.Lines.COGSCostingCode = LineRow(6).ToString
                    oDoc.Lines.CostingCode = LineRow(6).ToString
                Else
                    oDoc.Lines.COGSCostingCode2 = LineRow(6).ToString
                    oDoc.Lines.CostingCode2 = LineRow(6).ToString
                End If
            Next

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Adding API.", sFuncName)
            lRetCode = oDoc.Add
            If lRetCode <> 0 Then
                oCompany.GetLastError(lErrCode, sErrDesc)
                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Adding API failed.", sFuncName)
                Throw New ArgumentException(sErrDesc)
            End If

            oCompany.GetNewObjectCode(iAPInvNo)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Fucntion Completed Succesfully.", sFuncName)
            AddAPInvoice = RTN_SUCCESS

        Catch ex As Exception
            AddAPInvoice = RTN_ERROR
            sErrDesc = "Failed to Add AP Invoice " & ex.Message
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile("Function completed with ERROR:" & sErrDesc, sFuncName)
        End Try
    End Function

    Private Function AddAPInvoice_Copayment(ByVal oCompany As SAPbobsCOM.Company, _
                                  ByVal DtRow As DataRow, _
                                  ByVal oDvDtl As DataView, _
                                  ByRef iAPInvNo As Integer, _
                                  ByVal sFileName As String, _
                                  ByRef sErrDesc As String) As Long

        Dim sFuncName As String = "AddAPInvoice_Copayment"
        Dim sCardCode As String = String.Empty
        Dim oDoc As SAPbobsCOM.Documents
        Dim iCnt As Integer
        Dim lRetCode, lErrCode As Long
        Dim sBatchNo As String = String.Empty
        Dim sBatchPeriod As String = String.Empty
        Dim sRemarks As String = String.Empty
        Dim oRs As SAPbobsCOM.Recordset
        Dim sCostCenter As String = String.Empty

        Try
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting Function", sFuncName)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Creating DIAPI API Object", sFuncName)
            oDoc = oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oPurchaseInvoices)
            oRs = oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.BoRecordset)

            oDoc.DocType = SAPbobsCOM.BoDocumentTypes.dDocument_Service

            dtBP.DefaultView.RowFilter = "CardCode = '" & DtRow.Item(4).ToString & "'"
            If dtBP.DefaultView.Count = 0 Then
                sErrDesc = "Cardcode ::" & DtRow.Item(4).ToString & " provided does not exist in SAP."
                Call WriteToLogFile(sErrDesc, sFuncName)
                Throw New ArgumentException(sErrDesc)
            End If

            dtPURHDr.DefaultView.RowFilter = "U_AI_RefDocNum = '" & DtRow.Item(2).ToString & "'"
            If dtPURHDr.DefaultView.Count <> 0 Then
                sErrDesc = "Document NO ::" & DtRow.Item(2).ToString & " already exist in SAP."
                Call WriteToLogFile(sErrDesc, sFuncName)
                Throw New ArgumentException(sErrDesc)
            End If

            oDoc.CardCode = DtRow.Item(4).ToString
            oDoc.DocDate = DtRow.Item(3)
            oDoc.DocDueDate = DtRow.Item(3)
            oDoc.TaxDate = DtRow.Item(3)
            oDoc.NumAtCard = DtRow.Item(5).ToString
            oDoc.Comments = DtRow.Item(6).ToString
            oDoc.DocRate = CDbl(DtRow.Item(12))
            oDoc.UserFields.Fields.Item("U_AI_APARUploadName").Value = sFileName

            oDoc.UserFields.Fields.Item("U_AI_RefDocNum").Value = DtRow.Item(2).ToString

            Dim DtlRows() As DataRow = oDvDtl.Table.Select("F1='" & DtRow.Item(2).ToString & "'")

            For Each LineRow As DataRow In DtlRows
                iCnt += 1
                If iCnt > 1 Then
                    oDoc.Lines.Add()
                End If

                dtAC.DefaultView.RowFilter = "AcctCode = '" & LineRow(1).ToString & "'"
                If dtAC.DefaultView.Count = 0 Then
                    sErrDesc = "AcctCode::" & LineRow(2).ToString & "  provided does not exist in SAP."
                    Call WriteToLogFile(sErrDesc, sFuncName)
                    Throw New ArgumentException(sErrDesc)
                End If


                oDoc.Lines.AccountCode = LineRow(1).ToString
                oDoc.Lines.ItemDescription = LineRow(2).ToString
                oDoc.Lines.LineTotal = CDbl(LineRow(5))

                If CDbl(DtRow.Item(9)) > 0 Then
                    oDoc.Lines.VatGroup = "SI"
                Else
                    oDoc.Lines.VatGroup = "ZI"
                End If

                sCostCenter = LineRow(6).ToString
                Dim sSQL As String = "SELECT T0.""PrcCode"" FROM OPRC T0 WHERE T0.""PrcCode""='" & sCostCenter & "' and T0.""DimCode"" =1"
                oRs.DoQuery(sSQL)
                If Not oRs.EoF Then
                    oDoc.Lines.COGSCostingCode = sCostCenter
                    oDoc.Lines.CostingCode = sCostCenter
                Else
                    oDoc.Lines.COGSCostingCode2 = sCostCenter
                    oDoc.Lines.CostingCode2 = sCostCenter
                End If
            Next

            'Additonal Line for Co-Payment with Negative figure 11th Nov 2014
            oDoc.Lines.Add()
            oDoc.Lines.AccountCode = "5-62000-00"
            oDoc.Lines.ItemDescription = "Co-Payment"
            oDoc.Lines.LineTotal = -1 * CDbl(DtRow.Item(15))
            oDoc.Lines.VatGroup = "ZI"

            If Not oRs.EoF Then
                oDoc.Lines.COGSCostingCode = sCostCenter
                oDoc.Lines.CostingCode = sCostCenter
            Else
                oDoc.Lines.COGSCostingCode2 = sCostCenter
                oDoc.Lines.CostingCode2 = sCostCenter
            End If


            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Adding API.", sFuncName)
            lRetCode = oDoc.Add
            If lRetCode <> 0 Then
                oCompany.GetLastError(lErrCode, sErrDesc)
                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Adding API failed.", sFuncName)
                Throw New ArgumentException(sErrDesc)
            End If

            oCompany.GetNewObjectCode(iAPInvNo)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Fucntion Completed Succesfully.", sFuncName)
            AddAPInvoice_Copayment = RTN_SUCCESS

        Catch ex As Exception
            AddAPInvoice_Copayment = RTN_ERROR
            sErrDesc = "Failed to Add AP Invoice " & ex.Message
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile("Function completed with ERROR:" & sErrDesc, sFuncName)
        End Try
    End Function


    Private Function AddAPCreditNote(ByVal oCompany As SAPbobsCOM.Company, _
                                  ByVal DtRow As DataRow, _
                                  ByVal oDvDtl As DataView, _
                                  ByVal sFileName As String, _
                                  ByRef sErrDesc As String) As Long

        Dim sFuncName As String = "AddAPCreditNote"
        Dim sCardCode As String = String.Empty
        Dim oDoc As SAPbobsCOM.Documents
        Dim iCnt As Integer
        Dim lRetCode, lErrCode As Long
        Dim sBatchNo As String = String.Empty
        Dim sBatchPeriod As String = String.Empty
        Dim sRemarks As String = String.Empty

        Try
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting Function", sFuncName)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Creating DIAPI APCN Object", sFuncName)
            oDoc = oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oPurchaseCreditNotes)

            oDoc.DocType = SAPbobsCOM.BoDocumentTypes.dDocument_Service

            oDoc.CardCode = DtRow.Item(4).ToString
            oDoc.DocDate = DtRow.Item(3)
            oDoc.DocDueDate = DtRow.Item(3)
            oDoc.TaxDate = DtRow.Item(3)
            oDoc.NumAtCard = DtRow.Item(5).ToString
            oDoc.Comments = DtRow.Item(6).ToString
            oDoc.DocRate = CDbl(DtRow.Item(12))

            oDoc.UserFields.Fields.Item("U_AI_APARUploadName").Value = sFileName
            oDoc.UserFields.Fields.Item("U_AI_RefDocNum").Value = DtRow.Item(2).ToString

            Dim DtlRows() As DataRow = oDvDtl.Table.Select("F1='" & DtRow.Item(2).ToString & "'")

            For Each LineRow As DataRow In DtlRows
                iCnt += 1
                If iCnt > 1 Then
                    oDoc.Lines.Add()
                End If

                oDoc.Lines.AccountCode = LineRow(1).ToString
                oDoc.Lines.ItemDescription = LineRow(2).ToString
                oDoc.Lines.LineTotal = CDbl(LineRow(5)) * -1

                If CDbl(DtRow.Item(9)) > 0 Then
                    oDoc.Lines.VatGroup = "SI"
                Else
                    oDoc.Lines.VatGroup = "ZI"
                End If

                oDoc.Lines.COGSCostingCode2 = LineRow(6).ToString
                oDoc.Lines.CostingCode2 = DtRow(6).ToString
            Next

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Adding API.", sFuncName)
            lRetCode = oDoc.Add
            If lRetCode <> 0 Then
                oCompany.GetLastError(lErrCode, sErrDesc)
                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Adding API failed.", sFuncName)
                Throw New ArgumentException(sErrDesc)
            End If

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Fucntion Completed Succesfully.", sFuncName)
            AddAPCreditNote = RTN_SUCCESS

        Catch ex As Exception
            AddAPCreditNote = RTN_ERROR
            sErrDesc = ex.Message
            WriteToLogFile(sErrDesc, sFuncName)
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile("Function completed with ERROR:" & sErrDesc, sFuncName)
        End Try
    End Function

    Private Function AddOutgoingPayment(ByVal oCompany As SAPbobsCOM.Company, ByVal iInvNo As Integer, ByVal DtRow As DataRow, ByRef sErrdesc As String) As Long

        Dim sFuncName As String = "AddOutgoingPayment"
        Dim oPayment As SAPbobsCOM.IPayments
        Dim lRetCode, lErrCode As Long

        Try
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Starting Function..", sFuncName)

            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Retrieving Outgoing Payment Object", sFuncName)

            oPayment = oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oVendorPayments)
           
            oPayment.DocDate = DtRow.Item(3)

            oPayment.Invoices.SetCurrentLine(0)
            oPayment.Invoices.DocEntry = iInvNo
            oPayment.Invoices.InvoiceType = SAPbobsCOM.BoRcptInvTypes.it_PurchaseInvoice
            oPayment.Invoices.SumApplied = CDbl(DtRow.Item(15))
            'oPayment.Invoices.DistributionRule = DtRow.Item(13).ToString
            oPayment.Invoices.Add()

            oPayment.CardCode = DtRow.Item(4).ToString
            oPayment.CashSum = DtRow.Item(15)
            oPayment.CashAccount = "5-62000-00"
            oPayment.Remarks = DtRow.Item(14).ToString


            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Adding Outgoing Payment Document", sFuncName)
            lRetCode = oPayment.Add
            If lRetCode <> 0 Then
                oCompany.GetLastError(lErrCode, sErrdesc)
                If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Adding Outgoing paymnet failed.", sFuncName)
                Throw New ArgumentException(sErrdesc)
            End If

            AddOutgoingPayment = RTN_SUCCESS
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Fucntion completed successfully.", sFuncName)

        Catch ex As Exception
            AddOutgoingPayment = RTN_ERROR
            If p_iDebugMode = DEBUG_ON Then Call WriteToLogFile_Debug("Error in Procedure ProcForBP", sFuncName)
            Call WriteToLogFile(ex.Message, sFuncName)
        End Try
    End Function

End Module
